class User::CatalogController < ApplicationController
  before_filter :validate_ownership,       :except => [:index, :list, :get_picture, :get_folder_picture]

  def index
    if session[:user_id]
      @user = User.find(session[:user_id])
    else
      @user = nil
    end
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :index }

  def list
    session[:current_catalog_id] = params[:id] if params[:id]
    validate_current_catalog
    
    if params[:show_pictures]
      redirect_to(:controller => "user/picture", :action => "list")
    end
    
    @user = (session[:user_id]) ? User.find(session[:user_id]) : nil    
    
    @path = @current_catalog.get_path(4)
    
    # Get the number of the pictues we can see in this catalog.
    @picture_count = @current_catalog.pictures.select { |picture| picture.is_accessible?(@user_id) }.size
     
    catalogs = @current_catalog.children.select { |catalog| catalog.is_accessible?(@user_id) }
    @catalogs = WillPaginate::Collection.create((params[:page] or 1).to_i, 24) do |pager|
      pager.replace( catalogs[pager.offset, pager.per_page].to_a )
      
      unless pager.total_entries
        pager.total_entries = catalogs.size
      end
    end
  end

  def new
    @catalog = Catalog.new
  end

  def create
    @catalog = Catalog.new(:name   => params[:catalog][:name],
                   :description => params[:catalog][:description],
                   :owner  => User.find(@user_id),
                   :access => params[:catalog][:access],
                   :parent => @current_catalog)
    if @catalog.save
      @catalog.fix_access
      info 'Catalog was successfully created.', :notice
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @catalog = @current_catalog
  end

  def update
    if @current_catalog.parent
      name = params[:catalog][:name]
    else
      name = @current_catalog.name
    end
    if @current_catalog.update_attributes(:name   => name,
                   :description => params[:catalog][:description],
                   :access => params[:catalog][:access])
      @current_catalog.fix_access
      info 'Catalog was successfully updated.', :notice
      redirect_to :action => 'list'
    else
      render :action => 'edit'
    end
  end

  def destroy
    parent = @current_catalog.parent
    if parent
      Catalog.find(session[:current_catalog_id]).destroy_tree
      redirect_to :action => 'list', :id => parent.id
    else
      info "Cannot destroy root catalog"
      redirect_to :action => 'list'
    end
  end
end
